﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _85判断字符串的重复次数
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            string str = "AAABBAAA";  //AAA

            //第一种方式 把"AB"换成"",长度就减少了,用减少的长度/AB的长度 得到AB的次数

            //Indexof  可以从指定位置查找索引

            //第三种
            // Console.WriteLine(SameByIndex(str, "AB", 3));

            Console.WriteLine(RepeatTimes(str, "AA", true));

            Console.WriteLine(RepeatTimes1(str, "AAA"));
        }

        //Indexof
        private static int RepeatTimes1(string str, string subStr)
        {
            int startIndex = 0;
            int count = 0;
            while (true)
            {
                int index = str.IndexOf(subStr, startIndex);
                //  Console.WriteLine(index);
                if (index != -1)
                {
                    count++;
                    startIndex = index + subStr.Length;
                }
                else
                {
                    break;
                }
            }
            return count;
        }

        private static int RepeatTimes(string str, string subStr, bool jump = false)
        {
            int times = 0;
            for (int i = 0; i <= str.Length - subStr.Length; i++)
            {
                if (SameByIndex(str, subStr, i))
                {
                    times++;
                    if (jump)
                    {
                        i += subStr.Length - 1;
                    }
                }
            }

            return times;
        }
        //从指定位置判断是否和子字符串一样
        private static bool SameByIndex(string str, string subStr, int index)
        {
            for (int i = index; i < index + subStr.Length; i++)
            {
                if (str[i] != subStr[i - index])
                {
                    return false;
                }
            }
            return true;
        }
    }
}